package com.mdd.maduoduo.utils;

import android.content.Context;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.work.Worker;
import androidx.work.WorkerParameters;

import com.mdd.maduoduo.MyApplication;
import com.mdd.maduoduo.constants.CommonConstants;

import org.json.JSONObject;

import java.util.concurrent.TimeUnit;

import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class SmsUploadWorker extends Worker {

    private static final String TAG = "SmsUploadWorker";
    private static final String UPLOAD_URL = CommonConstants.API_PRODUCT_URL+"olda-shunshun-expressage-service/mddExpressPickupInfo/manualInput";

    public SmsUploadWorker(@NonNull Context context, @NonNull WorkerParameters workerParams) {
        super(context, workerParams);
    }

    @NonNull
    @Override
    public Result doWork() {
        Log.d(TAG, "Starting SMS upload work");

        String smsJson = getInputData().getString("sms_json");
        if (smsJson == null || smsJson.isEmpty()) {
            Log.w(TAG, "No SMS data to upload");
            return Result.failure();
        }

        try {
            // 创建OkHttp客户端
            OkHttpClient client = new OkHttpClient.Builder()
                    .connectTimeout(30, TimeUnit.SECONDS)
                    .writeTimeout(30, TimeUnit.SECONDS)
                    .readTimeout(30, TimeUnit.SECONDS)
                    .build();

            JSONObject json = new JSONObject();
            json.put("smsContent",smsJson);

            RequestBody body = RequestBody.create( MediaType.parse("application/json"),json.toString());
            // 创建请求
            Request request = new Request.Builder()
                    .url(UPLOAD_URL)
                    .post(body)
                    .addHeader("Authorization","Bearer "+ SpUtils.get(MyApplication.getContext(), CommonConstants.TOKEN))
                    .addHeader("Content-Type", "application/json")
                    .addHeader("Accept", "application/json")
                    .build();

            // 执行请求
            Response response = client.newCall(request).execute();

            if (response.isSuccessful()) {
                Log.d(TAG, "SMS upload successful");
                return Result.success();
            } else {
                Log.w(TAG, "SMS upload failed: " + response.code());
                return Result.retry();
            }
        } catch (Exception e) {
            Log.e(TAG, "SMS upload error", e);
            return Result.failure();
        }
    }
}
